package pCloud.service;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import pCloud.message.Message;
import pCloud.message.NumberMessage;

/**
 * Handle messages sent from the proxy back to the client
 * 
 */
public class ClientProxyServerProtHandle extends ProtocolHandle {

	int counter = 0;
	boolean printingData = true;
	long startTime; 
	String timeLogFile=null; 
	int nReplies = 1; //number of replies expected. This depends on the number of requested resources and 
						//if there's joining condition. 
	
	@Override
	public void receive(Object o) throws Exception {
		//System.out.println("End_time = " + System.currentTimeMillis());
		this.nReplies--;
		if (this.nReplies==0)
			this.outputTime(((Message)o).getMessageContent().getClass().getCanonicalName());
		handleProxyReplyMessage((Message) o);

		// this.conn.close();
		// this.communicator.removeConnection(this);
	}

	@Override
	public void send(Object m) throws Exception {
		conn.send(m);
	}

	private void handleProxyReplyMessage(Message m) throws Exception {
		if (m.getMessageType() != Message.PROXY_TO_CLIEN_MSG
				&& m.getMessageType() != Message.DATA_TO_PROXY_MSG) {
			System.err
					.println("PROXY_TO_CLIENT message expected, wrong type received "
							+ m.getMessageType());
			return;
		}
		this.communicator.getLogger().debug(
				m.getMessageContent() + " from " + m.getFrom());
		System.out.println("From " + m.getFrom());	
		System.out.println("printingData = "+this.printingData);
		if (!this.printingData){
			if (this.nReplies==0)
				this.conn.close();
			return;
		}
		
		if (m.getMessageType() == Message.DATA_TO_PROXY_MSG)
			System.out.println(((Message) m.getMessageContent())
					.getMessageContent());
		else
			System.out.println(m.getMessageContent());
		if (this.nReplies==0)
			this.conn.close();		
	}
	
	public void setNumberOfReplies(int nReplies){
		this.nReplies = nReplies;
		System.out.println("Number of replies = "+nReplies);
	}
	
	public void setPrintingDataOption(boolean b){
		this.printingData = b;
	}
	
	public void setTimeLogFile(String fileName){
		this.timeLogFile = fileName;
	}
	
	public void initStartTime(){
		this.startTime = System.currentTimeMillis();
	}
	
	private void outputTime(String messageClassName) throws IOException{
		long endTime = System.currentTimeMillis();
		double time = (endTime - startTime)*1.0/1000;
		if (this.timeLogFile!=null){
			PrintWriter writer = new PrintWriter(new FileWriter(this.timeLogFile,true));			
			writer.println(messageClassName+" "+this.startTime+" - "+endTime+" - "+time);
			writer.close();
		}
		else
			System.out.println("Time: "+this.startTime+" - "+endTime+ " - "+time);
		
	}
}
